package com.qfedu.filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 创建者: QF-SUN
 * 创建时间: 2023/3/27 9:54
 * 描述:
 *
 * 动物  dw = new  狗();
 *
 * 狗 g = dw;
 *
 *
 * 装箱:
 * 拆箱:
 *
 *
 *     /*  会拦截 所有资源， 包括jsp, servlet,html, jpg
 *     *.action: 只拦截带有.action 的请求
 *     /page/* : 只拦截 page中的请求路径
 *
 */
//@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("启动tomcat 初始化 过滤器");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("登录过滤器");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取 请求路径
        String requestURI = request.getRequestURI();
        if("/login.jsp".equals(requestURI) || "/login".equals(requestURI)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        System.out.println(request.getRequestURI());


        //如果session中可以找到用户信息，则认为已经登录，否则跳转到登录页面
        Object user = request.getSession().getAttribute("user");

        if(user == null) {
            response.sendRedirect("/login.jsp");
            return;
        }
        //filterChain： 过滤器链， 表示多个过滤器。
        //doFilter: 该过滤器执行完毕，执行下个过滤器(放行)
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("关闭tomcat时 销毁 过滤器");
    }
}
